package com.jingfu.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.PageResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.jingfu.common.ErrorCode;
import lombok.Getter;

import java.io.Serializable;
import java.time.Instant;

public class CommonResult<T> extends BaseResult implements Serializable {

    private static final long serialVersionUID = -8690123167018994049L;

    public CommonResult() {
    }
    public CommonResult(Builder builder) {
        this.setCode(builder.getCode());
        this.setMessage(builder.getMessage());
        this.setSuccess(builder.isSuccess());
        this.setData(builder.getData());
        this.setTimestamp(String.valueOf(Instant.now().toEpochMilli()));
    }

    public CommonResult(boolean success, String message) {
        this.setSuccess(success);
        this.setMessage(message);
    }

    public static Builder ok() {
        return new Builder().success(true).code("0").message("操作成功！");
    }

    public static Builder fail(ErrorCode errorCode) {
        return new Builder().success(false).code(String.valueOf(errorCode.getStatusCode())).message(errorCode.getReasonPhrase());
    }

    public static Builder fail(String code,String message) {
        return new Builder().success(false).code(code).message(message);
    }


    public static <T> CommonResult<T> ok(T body) {
        Builder builder = ok().data(body);
        return builder.build();
    }






    @Getter
    public static class Builder<T> {
        private boolean success = false;
        private String message;
        private T data;
        private String code;

        public Builder success(boolean success) {
            this.success = success;
            return this;
        }

        public Builder message(String message) {
            this.message = message;
            return this;
        }

        public Builder data(T data) {
            this.data = data;
            return this;
        }

        public Builder code(String code) {
            this.code = code;
            return this;
        }

        public CommonResult<T> build(){
            return new CommonResult<T>(this);
        }

    }



    public static void main(String[] args) throws JsonProcessingException {
        System.out.println(CommonResult.ok().build().toString());
        System.out.println(CommonResult.ok("dd"));
        System.out.println(CommonResult.fail(ErrorCode.VERTIFY_CODE_ERROR).build());
        PageResult<String> strings = new PageResult<>(1, 10, 5);
        strings.addAll(CollUtil.newArrayList("1","2","33"));
        System.out.println(strings);
    }


}
